﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Configuration;
using KishOnlineCommone;

public class MessageReader
{
    public static MessageDTO Get(MessageType Type, int Code)
    {
        return Read(Type, Code, MessageOwnerType.Client);
    }

    public static List<MessageDTO> List(List<MessageDTO> messages)
    {
        var result = new List<MessageDTO>();
        messages.ForEach(message =>
        {
            result.Add(Read(message.Type, message.Code, MessageOwnerType.Client));
        });
        return result;
    }

    private static MessageDTO Read(MessageType type, int messageCode, MessageOwnerType ownerType)
    {
        MessageDTO result = new MessageDTO();
        string xmlFile = System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["Messages"]);
        XDocument doc = XDocument.Load(xmlFile);
        var messageType = type.ToString().ToLower();
        var messages = from item in doc.Descendants(messageType)
                       where item.Attribute("code").Value == messageCode.ToString()
                       select new
                       {
                           ClientMessage = item.Elements("clientMessage").SingleOrDefault(),
                           ServerMessage = item.Elements("serverMessage").SingleOrDefault()
                       };
        var queryResult = messages.SingleOrDefault();
        if (queryResult.ClientMessage != null && ownerType == MessageOwnerType.Client)
            return new MessageDTO { Code= messageCode , Message = queryResult.ClientMessage.Value, Type = type, MessageOwnerType = ownerType };
        if (queryResult.ServerMessage != null && ownerType == MessageOwnerType.Server)
            return new MessageDTO { Code = messageCode, Message = queryResult.ServerMessage.Value, Type = type, MessageOwnerType = ownerType };
        
        
        //var messages = new
        //               {
        //                   ClientMessage =  "Test Client Meesage",
        //                   ServerMessage = "Test Server Message"
        //               };
        //var queryResult = messages;
        //if (queryResult.ClientMessage != null && ownerType == MessageOwnerType.Client)
        //    return new MessageDTO { Message = queryResult.ClientMessage, Type = type, MessageOwnerType = ownerType };
        //if (queryResult.ServerMessage != null && ownerType == MessageOwnerType.Server)
        //    return new MessageDTO { Message = queryResult.ServerMessage, Type = type, MessageOwnerType = ownerType };
        return null;
    }
}
